package mao.leetcode.others;

public class leetcode289 {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] a = {{1,1,1},{0,0,0},{0,0,0},{0,0,0}};
        solution.gameOfLife(a);
    }
    static class Solution {
        int m;
        int n;
        public void gameOfLife(int[][] board) {
            int[][] dir = {{-1,-1},{-1,0},{-1,1},
                    {0,-1},{0,1},
                    {1,-1},{1,0},{1,1}};
            m=board.length;
            if(m==0) {
                return;
            }
            n=board[0].length;
            int count;
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    count = countLiveNeighbors(i,j,dir,board);
                    if(board[i][j] == 1){
                        if(count<2 || count>3){
                            board[i][j] = 2;
                        }
                    }else if(board[i][j] == 0){
                        if(count == 3){
                            board[i][j] = -1;
                        }
                    }

                }
            }
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    if(board[i][j] == 2){
                        board[i][j] = 0;
                    }else if(board[i][j] == -1){
                        board[i][j]=1;
                    }

                }
            }



        }
        public int countLiveNeighbors(int i,int j,int[][] dir,int[][] board){
            int count = 0;
            int tmp_i,tmp_j;
            for(int[] a : dir){
                tmp_i=i+a[0];
                tmp_j=j+a[1];
                if(inAera(tmp_i,tmp_j)){
                    if(board[tmp_i][tmp_j]==1 || board[tmp_i][tmp_j]==2){
                        count++;
                    }
                }
            }
            return count;
        }
        public boolean inAera(int i,int j){
            if(i>=0 && i<m && j>=0 && j<n){
                return true;
            }
            return false;
        }
    }

}
